package com.ihighest.app.infox.activity;

import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import org.json.JSONArray;
import org.json.JSONException;

import com.ihighest.app.common.api.Api;
import com.ihighest.app.common.api.ApiCallback;
import com.ihighest.app.common.api.ApiParam;
import com.ihighest.app.common.api.ApiResult;
import com.ihighest.app.common.core.Application;
import com.ihighest.app.common.kit.AppKit;
import com.ihighest.app.common.kit.SharedPreferencesKit;
import com.ihighest.app.common.kit.ToastKit;
import com.ihighest.app.infox.Const;
import com.ihighest.app.infox.R;
import com.ihighest.app.infox.adapter.ChoosePlantsAdapter;
import com.ihighest.app.infox.bean.ProcessJson;
import com.ihighest.app.infox.myview.ActivityTitle;
import com.ihighest.app.infox.myview.CircleImageView;
import com.ihighest.app.infox.tools.CheckNetWork;
import com.ihighest.app.infox.tools.LoopListener;
import com.ihighest.app.infox.tools.LoopView;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import widget.OnWheelChangedListener;
import widget.WheelView;
import widget.adapters.ArrayWheelAdapter;

/**
 * 完善信息界面
 * 
 * @author lkx Created at 2015-11-23 下午5:46:09
 * @version 1.0
 */
public class PerfectInformationActivity extends ChooseAddressBaseActivity implements OnClickListener, OnWheelChangedListener {
	private static final int PHOTO_REQUEST_CAMERA = 1;// 拍照
	private static final int PHOTO_REQUEST_GALLERY = 2;// 从相册中选择
	private static final int PHOTO_REQUEST_CUT = 3;// 结果
	private static final int SELECT_CITY = 4;
	public static ArrayList<String> listId = new ArrayList<String>();
	public static ArrayList<String> names = new ArrayList<String>();
	private ActivityTitle title;
	private CircleImageView iconImageView;
	private EditText nameEditText, jobName;// 昵称工作单位
	private TextView myJob, area, plannts;// 职位,地区作物
	private PopupWindow mPopupWindow;
	private RelativeLayout.LayoutParams layoutParams;
	private LoopView loopView;
	private LinearLayout rootview;
	private String a;
	private Bitmap myBitmap;
	/* 头像名称 */
	private static final String PHOTO_FILE_NAME = "temp_photo.jpg";
	private File tempFile;
	private String mJob;
	private ArrayList<String> list;
	private String activityName;
	private View falesparent;
	private String ueseIcon;
	private String name;
	private WheelView mViewProvince;
	private WheelView mViewCity;
	private WheelView mViewDistrict;
	private Button mBtnConfirm;
	private PopupWindow addressPupo;
	private LinearLayout parent;
	private JSONArray alltags;
	private JSONArray metags;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Application.getInstance().addActivity(this);
		setContentView(R.layout.infox_activity_perfectinformation);

		inint();
		initData();
		alltags();
		initPopuWindow();
	}

	/**
	 * 获取会员信息初始数据
	 * 
	 * @author lkx Created at 2015-11-24 上午10:28:08
	 */
	private void initData() {
		if (!TextUtils.isEmpty(SharedPreferencesKit.getString(PerfectInformationActivity.this, Const.SP_KEY_USER_ID))) {
			String url = "member/info/m_" + SharedPreferencesKit.getString(PerfectInformationActivity.this, Const.SP_KEY_USER_ID) + ".json";
			Api.data(url, new ApiCallback(PerfectInformationActivity.this) {

				@Override
				public void handleSuccess(ApiResult result) {
					try {
						// String name = result.getData().getString("title");
						// String gender = result.getData().getString("sex");
						// String birth = result.getData().getString("bir");
						// String address = result.getData().getString("addr");
						// String eMail = result.getData().getString("mail");
						// String QQ = result.getData().getString("qq");
						//
						// String memo = result.getData().getString("memo");
						area.setText(result.getData().getString("area"));
						jobName.setText(result.getData().getString("company"));
						myJob.setText(result.getData().getString("profession"));
						// plannts.setText(result.getData().getString("cropNames"));
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

				}

				@Override
				public void handleFailure(Exception e, String msg) {
					// TODO Auto-generated method stub

				}
			}, PerfectInformationActivity.this);
		}
	}

	private void checkname(final String uname) {
		// TODO Auto-generated method stub
		Api.post("me/checkUnameExist", ApiParam.create().addParam("uname", uname), new ApiCallback(PerfectInformationActivity.this, true) {

			@Override
			public void handleSuccess(ApiResult result) {
				// TODO Auto-generated method stub
				if (result.getCode() == 100) {
					try {
						if (result.getData().getBoolean("result")) {
							ToastKit.showShort(PerfectInformationActivity.this, "该昵称已存在");
						} else {
							commitData(uname, mJob);

						}
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

				}
			}

			@Override
			public void handleFailure(Exception e, String msg) {
				// TODO Auto-generated method stub
				ToastKit.showShort(PerfectInformationActivity.this, "昵称校验失败，请重试");
			}
		}, PerfectInformationActivity.this);

	}

	private void inint() {
		title = (ActivityTitle) findViewById(R.id.perfectInformationTitle);
		title.setTitle("完善资料");
		ueseIcon = getIntent().getStringExtra("icon");
		name = getIntent().getStringExtra("name");
		title.setViewVersible(title.titleBack, title.rightText);
		title.setViewGone(title.titleMsg, title.titleRefresh);
		title.setRightTextViewText("完成");

		listId = new ArrayList<String>();
		names = new ArrayList<String>();
		title.rightText.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// 完成提交
				String nickName = nameEditText.getText().toString();
				if (nickName.length() > 8) {
					ToastKit.showShort(PerfectInformationActivity.this, "输入的昵称过长");
					return;
				}
				if (nickName.equals(name)) {
					commitData(nickName, mJob);

				} else {
					// name check
					checkname(nickName);
				}

			}
		});
		tempFile = new File(Environment.getExternalStorageDirectory(), PHOTO_FILE_NAME);
		iconImageView = (CircleImageView) findViewById(R.id.perfectInformationUserIcon);
		nameEditText = (EditText) findViewById(R.id.perfectInformationUserName);
		jobName = (EditText) findViewById(R.id.perfectInformationUserJobName);

		myJob = (TextView) findViewById(R.id.perfectInformationUserJob);
		plannts = (TextView) findViewById(R.id.perfectInformationUserLikePlants);
		area = (TextView) findViewById(R.id.perfectInformationUserArea);
		findViewById(R.id.choosePlant).setOnClickListener(this);
		findViewById(R.id.chooseArea).setOnClickListener(this);
		findViewById(R.id.choosePlant).setOnClickListener(this);
		String from = getIntent().getStringExtra("personActivity");

		iconImageView.setOnClickListener(this);

		findViewById(R.id.chooseJob).setOnClickListener(this);

		if (!TextUtils.isEmpty(name)) {
			nameEditText.setText(name);
			nameEditText.setSelection(name.length());
			nameEditText.setEnabled(false);
			String profession = SharedPreferencesKit.getString(this, Const.PROFESSION);
			AppKit.SetUserImg(ueseIcon, iconImageView);
			myJob.setText(profession);

		}

		getData();
		// findViewById(R.id.button1).setOnClickListener(new OnClickListener() {
		//
		// @Override
		// public void onClick(View arg0) {
		// Intent intent = new Intent(PerfectInformationActivity.this,
		// AlertInfoActivity.class);
		// startActivity(intent);
		//
		// }
		// });
	}

	private void getData() {
		Api.data("position_type_list.json", new ApiCallback(this) {

			@Override
			public void handleSuccess(ApiResult result) {
				list = new ArrayList<String>();
				if (result.getDatas() != null) {
					for (int i = 0; i < result.getDatas().length(); i++) {
						try {
							list.add(result.getDatas().get(i).toString());
						} catch (JSONException e) {
							e.printStackTrace();
						}
					}

				}
				initPupoVindow();

			}

			@Override
			public void handleFailure(Exception e, String msg) {

			}
		}, PerfectInformationActivity.this);

	}

	private void initData(View v) {
		layoutParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 150);
		layoutParams.addRule(RelativeLayout.ALIGN_PARENT_TOP);

		rootview = (LinearLayout) v.findViewById(R.id.mRootView);

		falesparent = v.findViewById(R.id.id_falseparent);
		falesparent.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				mPopupWindow.dismiss();
			}
		});

		loopView = new LoopView(this);
		TextView view = new TextView(PerfectInformationActivity.this);
		view.setLayoutParams(new LayoutParams(layoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
		view.setBackgroundResource(R.drawable.infox_send_back);
		view.setText("确定");
		view.setTextSize(20.0f);
		view.setTextColor(Color.WHITE);
		view.setGravity(Gravity.CENTER);

		// 设置是否循环播放
		loopView.setNotLoop();
		// 滚动监听
		loopView.setListener(new LoopListener() {

			@Override
			public void onItemSelect(int item) {
				a = list.get(item);
			}
		});
		// 设置原始数据
		loopView.setArrayList(list);
		// 设置初始位置
		loopView.setPosition(0);
		// 设置字体大小
		loopView.setTextSize(16);
		rootview.addView(loopView, layoutParams);
		rootview.addView(view);
		view.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				int selectItem = loopView.selectItem();
				mJob = list.get(selectItem);
				myJob.setText(list.get(selectItem));
				// Toast.makeText(PerfectInformationActivity.this,
				// list.get(selectItem), 0).show();
				mPopupWindow.dismiss();
			}
		});
	}

	private void initPupoVindow() {
		LayoutInflater layoutInflater = LayoutInflater.from(this);
		View popupWindow = layoutInflater.inflate(R.layout.infox_pupopwindow_scrollitem_layout, null);
		initData(popupWindow);

		// 创建一个PopupWindow
		// 参数1：contentView 指定PopupWindow的内容
		// 参数2：width 指定PopupWindow的width
		// 参数3：height 指定PopupWindow的height
		mPopupWindow = new PopupWindow(popupWindow, android.view.ViewGroup.LayoutParams.MATCH_PARENT,
				android.view.ViewGroup.LayoutParams.MATCH_PARENT);
		// 必须设置背景
		mPopupWindow.setBackgroundDrawable(new BitmapDrawable());
		// 设置点击其他地方 就消失 (只设置这个，没有效果)

		mPopupWindow.setOutsideTouchable(true); /* 设置触摸外面时消失 */
	}

	private void showPupop() {

		if (mPopupWindow == null) {
			initPupoVindow();
			mPopupWindow.showAtLocation(PerfectInformationActivity.this.findViewById(R.id.id_parent_view), Gravity.CENTER, 0, 0);
		} else {
			if (mPopupWindow.isShowing()) {
				mPopupWindow.dismiss();
			} else {
				mPopupWindow.showAtLocation(PerfectInformationActivity.this.findViewById(R.id.id_parent_view), Gravity.BOTTOM
						| Gravity.CENTER_HORIZONTAL, 0, 0);
			}

		}

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.view.View.OnClickListener#onClick(android.view.View)
	 * 
	 * @author lkx Created at 2015-10-17 下午5:49:21
	 */
	@Override
	public void onClick(View arg0) {
		// TODO Auto-generated method stub
		switch (arg0.getId()) {
		case R.id.perfectInformationUserIcon:
			// 选择图像
			// PopupWindow

			// PictureUtil.doPickPhotoAction(PerfectInformationActivity.this);
			new AlertDialog.Builder(this).setTitle("选择图片获取方式").setNegativeButton("相册", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();

					// 激活系统图库，选择一张图片
					Intent intent = new Intent(Intent.ACTION_PICK);
					intent.setType("image/*");
					startActivityForResult(intent, PHOTO_REQUEST_GALLERY);

				}
			}).setPositiveButton("拍照", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int whichButton) {

					Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
					// 判断存储卡是否可以用，可用进行存储
					if (hasSdcard()) {

						intent.putExtra(MediaStore.EXTRA_OUTPUT,
								Uri.fromFile(new File(Environment.getExternalStorageDirectory(), PHOTO_FILE_NAME)));
					}
					startActivityForResult(intent, PHOTO_REQUEST_CAMERA);
				}
			}).show();
			// Intent intent = new Intent(
			// "android.media.action.IMAGE_CAPTURE");
			// // 判断存储卡是否可以用，可用进行存储
			// if (hasSdcard()) {
			// ContentValues values = new ContentValues();
			// photoUri = PerfectInformationActivity.this
			// .getContentResolver()
			// .insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
			// values);
			// intent.putExtra(
			// MediaStore.EXTRA_OUTPUT,
			// Uri.fromFile(new File(
			// Environment
			// .getExternalStorageDirectory(),
			// PHOTO_FILE_NAME)));
			// }
			// startActivityForResult(intent,
			// PHOTO_REQUEST_CAMERA);
			//
			// }
			// }).show();

			break;

		case R.id.chooseJob:
			showPupop();
			break;

		case R.id.chooseArea:
			if (addressPupo == null) {
				initPopuWindow();
				if (addressPupo.isShowing()) {
					addressPupo.dismiss();
				} else {
					addressPupo.showAtLocation(findViewById(R.id.id_parent_view), Gravity.CENTER | Gravity.CENTER_HORIZONTAL, 0, 0);
				}
			} else {
				if (addressPupo.isShowing()) {
					addressPupo.dismiss();
				} else {
					addressPupo.showAtLocation(findViewById(R.id.id_parent_view), Gravity.CENTER | Gravity.CENTER_HORIZONTAL, 0, 0);
				}
			}

			// Intent cityintent = new Intent(PerfectInformationActivity.this,
			// Selectcity.class);
			// startActivityForResult(cityintent, SELECT_CITY);

			break;
		case R.id.choosePlant:

			// plannts.setText("");
			Intent plantIntent = new Intent(PerfectInformationActivity.this, ChoosePlantsActivity.class);
			startActivity(plantIntent);
			break;
		case R.id.btn_confirm:
			/** 隐藏软键盘 **/
			View view = getWindow().peekDecorView();
			if (view != null) {
				InputMethodManager inputmanger = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
				inputmanger.hideSoftInputFromWindow(view.getWindowToken(), 0);
			}
			showSelectedResult();
			addressPupo.dismiss();
			break;

		case R.id.id_parent:

			addressPupo.dismiss();
			break;
		}

	}

	/**
	 * 提交昵称和职位数据
	 * 
	 * @param name
	 * @param job
	 * @author lkx Created at 2015-10-17 下午5:49:24
	 */
	private void commitData(final String name, String job) {
		ApiParam param = ApiParam.create();

		String s = null;
		try {
			s = SharedPreferencesKit.getJsonObject(PerfectInformationActivity.this, Const.SP_KEY_CONFIG_JSON)
					.getString("reg_optional_step");
		} catch (JSONException e1) {
			e1.printStackTrace();
		}
		param.addParam("apiver", "2");
		if (TextUtils.isEmpty(name)) {
			ToastKit.showShort(getApplicationContext(), "请输入昵称");
		} else {

			param.addParam("nickname", name);
			if (!TextUtils.isEmpty(job)) {
				param.addParam("profession", job);
			}

			if (!TextUtils.isEmpty(jobName.getText().toString())) {
				// 单位名称
				param.addParam("company", jobName.getText().toString());
			}
			if (!TextUtils.isEmpty(area.getText().toString())) {
				// 地区
				param.addParam("area", area.getText().toString());
			}
			if (!TextUtils.isEmpty(plannts.getText().toString())) {
				// 关注作物
				// param.addParam("cropIds",
				// AppKit.listToString(ChoosePlantsActivity.listId));
			}

			title.rightText.setClickable(false);
			Api.post("me/update", param, new ApiCallback(PerfectInformationActivity.this) {

				@Override
				public void handleSuccess(ApiResult result) {

					if (result.getCode() == 100) {
						finish();
					} else {
						title.rightText.setClickable(true);
					}

				}

				@Override
				public void handleFailure(Exception e, String msg) {
					title.rightText.setClickable(true);
				}
			}, PerfectInformationActivity.this);

		}

	}

	/**
	 * 图片上传
	 * 
	 * @author lkx Created at 2015-10-17 下午2:45:38
	 */
	private void upload() {
		if (myBitmap != null) {

			File fTemp = null;

			try {
				fTemp = File.createTempFile("letter", ".jpg");
				BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(fTemp));

				myBitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
				bos.flush();
				bos.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			ApiParam param = ApiParam.create();
			param.addParam("file", fTemp);
			Api.post("me/uploadAvatar", param, new ApiCallback(PerfectInformationActivity.this) {

				@Override
				public void handleSuccess(ApiResult result) {
					if (result.getCode() == 100) {
						try {
							SharedPreferencesKit.putString(mContext, Const.SP_KEY_USER_HEADER, result.getData().getString("header"));
							AppKit.refreshRongIMUser(mContext);
						} catch (JSONException e) {
							Log.e(TAG, e.getMessage(), e);
						}
					}
				}

				@Override
				public void handleFailure(Exception e, String msg) {
				}
			}, PerfectInformationActivity.this);
		}

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == PHOTO_REQUEST_GALLERY) {
			if (data != null) {
				// 得到图片的全路径

				Uri uri = data.getData();
				crop(uri);
			}

		} else if (requestCode == PHOTO_REQUEST_CAMERA) {
			if (hasSdcard()) {

				crop(Uri.fromFile(tempFile));
			} else {
				ToastKit.showShort(PerfectInformationActivity.this, "未找到存储卡，无法存储照片！");
			}

		} else if (requestCode == PHOTO_REQUEST_CUT) {
			try {
				myBitmap = data.getParcelableExtra("data");
				this.iconImageView.setImageBitmap(myBitmap);
				upload();
				boolean delete = tempFile.delete();

			} catch (Exception e) {
				e.printStackTrace();
			}

		} else if (requestCode == SELECT_CITY) {
			try {
				String adress = data.getStringExtra("adress");
				System.out.println(adress);
				// city=data.getStringExtra("city");
				area.setText(adress);

			} catch (Exception e) {
			}

		}

		super.onActivityResult(requestCode, resultCode, data);
	}

	// 得到系统当前时间并转化为字符串
	@SuppressLint("SimpleDateFormat")
	public static String getCharacterAndNumber() {
		String rel = "";
		SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
		Date curDate = new Date(System.currentTimeMillis());
		rel = formatter.format(curDate);
		return rel;
	}

	/**
	 * 是否存在sd卡
	 * 
	 * @return
	 * @author lkx Created at 2015-10-17 上午10:53:34
	 */
	private boolean hasSdcard() {
		if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 图片裁剪
	 * 
	 * @param uri
	 * @author lkx Created at 2015-10-17 上午10:58:44
	 */
	private void crop(Uri uri) {
		// 裁剪图片意图
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(uri, "image/*");
		intent.putExtra("crop", "true");
		// 裁剪框的比例，1：1
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		// 裁剪后输出图片的尺寸大小
		intent.putExtra("outputX", 250);
		intent.putExtra("outputY", 250);
		// 图片格式
		intent.putExtra("outputFormat", "JPEG");
		intent.putExtra("noFaceDetection", true);// 取消人脸识别
		intent.putExtra("return-data", true);// true:不返回uri，false：返回uri
		startActivityForResult(intent, PHOTO_REQUEST_CUT);
	}

	@Override
	public void onResume() {

		if (listId != null) {
			if (listId.size() > 0) {
				plannts.setText(AppKit.listToString(names));
			}
		}
		super.onResume();
	}

	@Override
	public void onBackPressed() {
		if (addressPupo != null && addressPupo.isShowing()) {

			addressPupo.dismiss();

		} else {
			finish();
		}

	}

	private void initPopuWindow() {
		LayoutInflater inflater = LayoutInflater.from(this);
		View popupWindow = inflater.inflate(R.layout.infox_choosesddress_populayout, null);
		addressPupo = new PopupWindow(popupWindow, android.view.ViewGroup.LayoutParams.MATCH_PARENT,
				android.view.ViewGroup.LayoutParams.MATCH_PARENT);
		// 必须设置背景
		addressPupo.setBackgroundDrawable(new BitmapDrawable());
		// 设置点击其他地方 就消失 (只设置这个，没有效果)

		addressPupo.setOutsideTouchable(true); /* 设置触摸外面时消失 */

		setUpViews(popupWindow);
		setUpListener();
		setUpData();

	}

	private void setUpViews(View view) {
		mViewProvince = (WheelView) view.findViewById(R.id.id_province);
		mViewCity = (WheelView) view.findViewById(R.id.id_city);
		mViewDistrict = (WheelView) view.findViewById(R.id.id_district);
		mBtnConfirm = (Button) view.findViewById(R.id.btn_confirm);
		parent = (LinearLayout) view.findViewById(R.id.id_parent);

	}

	private void setUpListener() {
		// 添加change事件
		mViewProvince.addChangingListener(this);
		// 添加change事件
		mViewCity.addChangingListener(this);
		// 添加change事件
		mViewDistrict.addChangingListener(this);
		// 添加onclick事件
		mBtnConfirm.setOnClickListener(this);
		parent.setOnClickListener(this);
	}

	private void setUpData() {
		// initProvinceDatas();
		// getCityList();
		// getDate(SharedPreferencesKit.getString(PerfectInformationActivity.this,
		// "address"));

		if (TextUtils.isEmpty(SharedPreferencesKit.getString(PerfectInformationActivity.this, "address"))) {
			// 获取数据
			System.out.println("+++++++++++++++++++");
			Api.data("area_provincial_city_county.json", new ApiCallback(PerfectInformationActivity.this) {
				@Override
				public void handleFailure(Exception e, String msg) {

				}

				@Override
				public void handleSuccess(ApiResult result) {
					SharedPreferencesKit.putString(PerfectInformationActivity.this, "address", result.getDatas().toString());
					getCityList(result.getDatas().toString());

					mViewProvince.setViewAdapter(new ArrayWheelAdapter<String>(PerfectInformationActivity.this, mProvinceDatas));
					// 设置可见条目数量
					mViewProvince.setVisibleItems(7);
					mViewCity.setVisibleItems(7);
					mViewDistrict.setVisibleItems(7);
					updateCities();
					updateAreas();
				}
			}, PerfectInformationActivity.this);

		} else {
			getCityList(SharedPreferencesKit.getString(PerfectInformationActivity.this, "address"));

			mViewProvince.setViewAdapter(new ArrayWheelAdapter<String>(PerfectInformationActivity.this, mProvinceDatas));
			// 设置可见条目数量
			mViewProvince.setVisibleItems(7);
			mViewCity.setVisibleItems(7);
			mViewDistrict.setVisibleItems(7);
			updateCities();
			updateAreas();
		}

		//
		// mViewProvince.setViewAdapter(new
		// ArrayWheelAdapter<String>(PerfectInformationActivity.this,
		// mProvinceDatas));
		// // 设置可见条目数量
		// mViewProvince.setVisibleItems(7);
		// mViewCity.setVisibleItems(7);
		// mViewDistrict.setVisibleItems(7);
		// updateCities();
		// updateAreas();
	}

	@Override
	public void onChanged(WheelView wheel, int oldValue, int newValue) {
		// TODO Auto-generated method stub
		if (wheel == mViewProvince) {
			updateCities();
		} else if (wheel == mViewCity) {
			updateAreas();
		} else if (wheel == mViewDistrict) {
			mCurrentDistrictName = mDistrictDatasMap.get(mCurrentCityName)[newValue];
			mCurrentDistrictCode = mXianjicodeDatasMap.get(mCurrentDistrictName);
		}
	}

	/**
	 * 根据当前的市，更新区WheelView的信息
	 */
	private void updateAreas() {
		int pCurrent = mViewCity.getCurrentItem();
		mCurrentCityName = mCitisDatasMap.get(mCurrentProviceName)[pCurrent];
		String[] areas = mDistrictDatasMap.get(mCurrentCityName);

		if (areas == null) {
			areas = new String[] { "" };
		}
		mViewDistrict.setViewAdapter(new ArrayWheelAdapter<String>(this, areas));
		mViewDistrict.setCurrentItem(0);
		mCurrentDistrictName = areas[0];
		mCurrentDistrictCode = mXianjicodeDatasMap.get(mCurrentDistrictName);
	}

	/**
	 * 根据当前的省，更新市WheelView的信息
	 */
	private void updateCities() {
		int pCurrent = mViewProvince.getCurrentItem();
		mCurrentProviceName = mProvinceDatas[pCurrent];
		String[] cities = mCitisDatasMap.get(mCurrentProviceName);
		if (cities == null) {
			cities = new String[] { "" };
		}
		mViewCity.setViewAdapter(new ArrayWheelAdapter<String>(this, cities));
		mViewCity.setCurrentItem(0);
		updateAreas();
	}

	private void showSelectedResult() {
		String address = "";
		if (!TextUtils.isEmpty(mCurrentProviceName)) {

			mCurrentProviceCode = mShengJicodeDatasMap.get(mCurrentProviceName);
		}
		if (!TextUtils.isEmpty(mCurrentCityName)) {

			mCurrentCityCode = mShijiCodeMap.get(mCurrentCityName);
		}
		if (!TextUtils.isEmpty(mCurrentDistrictName)) {

			mCurrentDistrictCode = mXianjicodeDatasMap.get(mCurrentDistrictName);
		}
		// Toast.makeText(PerfectInformationActivity.this,
		// "当前选中:" + mCurrentProviceName + "," + mCurrentCityName + "," +
		// mCurrentDistrictName + "," + mCurrentZipCode,
		// Toast.LENGTH_SHORT).show();
		System.out.println("当前选中:" + mCurrentProviceCode + "," + mCurrentCityCode + "," + mCurrentDistrictCode);
		if (!TextUtils.isEmpty(mCurrentProviceName)) {
			mCurrentProviceCode = mShengJicodeDatasMap.get(mCurrentProviceName);
			address = mCurrentProviceName;
			if (!TextUtils.isEmpty(mCurrentCityName)) {
				address = address + mCurrentCityName;
				mCurrentCityCode = mShijiCodeMap.get(mCurrentCityName);
				if (!TextUtils.isEmpty(mCurrentDistrictName) && (!mCurrentDistrictName.equals("--"))) {
					address = address + mCurrentDistrictName;
					mCurrentDistrictCode = mXianjicodeDatasMap.get(mCurrentDistrictName);
				}
			}
			area.setText(address);
		}

	}

	/**
	 * 获取已登录会员绑定数据
	 */
	private void getmetags() {
		Api.get("me/info", ApiParam.create(), new ApiCallback(this) {

			@Override
			public void handleSuccess(ApiResult result) {

				try {
					metags = result.getData().getJSONArray("tags");
					SharedPreferencesKit.putJsonArray(getApplicationContext(), Const.TAGS, result.getData().getJSONArray("tags"));
					
					
					for (int i = 0; i < metags.length(); i++) {
						String tagid = metags.getString(i);
						for (int j = 0; j < alltags.length(); j++) {
							JSONArray array = alltags.getJSONObject(j).getJSONArray("sub");
							for (int q = 0; q < array.length(); q++) {
								if (tagid.equals(array.getJSONObject(q).getString("id"))) {

									System.out.println("++++++++已订阅的标签+++++" + i);
									listId.add(array.getJSONObject(q).getString("id"));
									names.add(array.getJSONObject(q).getString("title"));

								}

							}

						}

					}

					plannts.setText(AppKit.listToString(names));
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}

			@Override
			public void handleFailure(Exception e, String msg) {

			}
		}, this);

	}

	/**
	 * 
	 * 获取所有标签列表
	 * 
	 * 
	 * @author yyh Created at 2015-12-8 上午11:07:50
	 */
	private void alltags() {
		if (CheckNetWork.isConnected(PerfectInformationActivity.this)) {
			// 如果网络正常
			Api.data("tag_recommend_list.json", new ApiCallback(this, true) {

				@Override
				public void handleSuccess(ApiResult result) {

					alltags = result.getDatas();
					// SharedPreferencesKit.putJsonArray(getApplicationContext(),
					// Const.TAGS, result.getDatas());
					getmetags();

				}

				@Override
				public void handleFailure(Exception e, String msg) {
					// TODO Auto-generated method stub

				}
			}, this);

		}

	}

}
